<template>
  <div class="register">
    <!-- 注册页头部 -->
    <div class="register-header">
      <div class="flex-y-center">
        <el-switch
          v-model="isDark"
          inline-prompt
          active-icon="Moon"
          inactive-icon="Sunny"
          @change="toggleTheme"
        />
        <lang-select class="ml-2 cursor-pointer" />
      </div>
    </div>

    <!-- 注册页内容 -->
    <div class="register-form">
      <el-form ref="registerFormRef" :model="registerFormData" :rules="registerRules">
        <div class="form-title">
          <h2>{{ defaultSettings.title }} - 用户注册</h2>
        </div>

        <!-- 用户名 -->
        <el-form-item prop="username">
          <div class="input-wrapper">
            <el-icon class="mx-2">
              <User />
            </el-icon>
            <el-input
              v-model="registerFormData.username"
              placeholder="请输入用户名"
              name="username"
              size="large"
              class="h-[48px]"
            />
          </div>
        </el-form-item>

        <!-- 密码 -->
        <el-tooltip :visible="isCapslock" :content="$t('register.capsLock')" placement="right">
          <el-form-item prop="password">
            <div class="input-wrapper">
              <el-icon class="mx-2">
                <Lock />
              </el-icon>
              <el-input
                v-model="registerFormData.password"
                placeholder="请输入密码"
                type="password"
                name="password"
                size="large"
                class="h-[48px] pr-2"
                show-password
                @keyup="checkCapslock"
              />
            </div>
          </el-form-item>
        </el-tooltip>

        <!-- 确认密码 -->
        <el-form-item prop="confirmPassword">
          <div class="input-wrapper">
            <el-icon class="mx-2">
              <Lock />
            </el-icon>
            <el-input
              v-model="registerFormData.confirmPassword"
              placeholder="确认密码"
              type="password"
              name="confirmPassword"
              size="large"
              class="h-[48px] pr-2"
              show-password
              @keyup.enter="handleRegisterSubmit"
            />
          </div>
        </el-form-item>

        <!-- 姓名 -->
        <el-form-item prop="name">
          <div class="input-wrapper">
            <el-icon class="mx-2">
              <Edit />
            </el-icon>
            <el-input
              v-model="registerFormData.name"
              placeholder="请输入姓名"
              name="name"
              size="large"
              class="h-[48px]"
            />
          </div>
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item prop="phone">
          <div class="input-wrapper">
            <el-icon class="mx-2">
              <Iphone />
            </el-icon>
            <el-input
              v-model="registerFormData.phone"
              placeholder="请输入手机号"
              name="phone"
              size="large"
              class="h-[48px]"
            />
          </div>
        </el-form-item>

        <!-- 头像上传 -->
        <el-form-item label="头像上传" prop="avatar">
          <SingleImageUpload v-model="registerFormData.avatar" />
        </el-form-item>
        <!-- 角色选择 -->
        <el-form-item prop="role_id">
          <div class="input-wrapper">
            <el-icon class="mx-2">
              <UserFilled />
            </el-icon>
            <el-select
              v-model="registerFormData.role_id"
              placeholder="请选择角色"
              size="large"
              class="w-full"
            >
              <el-option label="商家" :value="2" />
              <el-option label="管理员" :value="1" />
            </el-select>
          </div>
        </el-form-item>

        <!-- 注册按钮 -->
        <el-button
          :loading="loading"
          type="primary"
          size="large"
          class="w-full"
          @click.prevent="handleRegisterSubmit"
        >
          立即注册
        </el-button>

        <div class="mt-4 text-center text-sm text-gray-500">
          已有账号？
          <el-link type="primary" href="/login">立即登录</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { User, Lock, Edit, Iphone, Picture, UserFilled, Plus } from "@element-plus/icons-vue";
import defaultSettings from "@/settings";
import UsersAPI from "@/api/system/user";
import { ThemeEnum } from "@/enums/ThemeEnum";
import { useSettingsStore } from "@/store";

const settingsStore = useSettingsStore();
const router = useRouter();
const { t } = useI18n();
const registerFormRef = ref();

const isDark = ref(settingsStore.theme === ThemeEnum.DARK);
const loading = ref(false);
const isCapslock = ref(false);

const registerFormData = ref({
  username: "",
  password: "",
  confirmPassword: "",
  name: "",
  phone: "",
  avatar: "",
  role_id: 2,
});

const registerRules = computed(() => {
  return {
    username: [
      { required: true, message: "用户名不能为空", trigger: "blur" },
      { min: 4, max: 20, message: "用户名长度应在4到20个字符之间", trigger: "blur" },
    ],
    password: [
      { required: true, message: "密码不能为空", trigger: "blur" },
      { min: 6, message: "密码长度不能少于6个字符", trigger: "blur" },
    ],
    confirmPassword: [
      { required: true, message: "确认密码不能为空", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value !== registerFormData.value.password) {
            callback(new Error("两次输入的密码不一致"));
          } else {
            callback();
          }
        },
        trigger: "blur",
      },
    ],
    name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    phone: [
      { required: true, message: "手机号码不能为空", trigger: "blur" },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "手机号码格式不正确，请输入有效的中国大陆手机号",
        trigger: "blur",
      },
    ],
    role_id: [{ required: true, message: "请选择用户角色", trigger: "change" }],
  };
});
// 处理头像上传
const handleAvatarChange = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    registerFormData.value.avatar = e.target.result;
  };
  reader.readAsDataURL(file.raw);
};

// 注册提交
const handleRegisterSubmit = () => {
  registerFormRef.value?.validate((valid) => {
    if (valid) {
      loading.value = true;
      // 这里调用注册API
      UsersAPI.add(registerFormData.value)
        .then(() => {
          ElMessage.success("注册成功");
          router.push("/login");
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
};

// 主题切换
const toggleTheme = () => {
  const newTheme = settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK;
  settingsStore.changeTheme(newTheme);
};

// 检查输入大小写
const checkCapslock = (event) => {
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState("CapsLock");
  }
};
</script>

<style lang="scss" scoped>
.register {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  padding: 20px;
  overflow-y: auto;
  background: url("@/assets/images/login-bg.jpg") no-repeat;
  background-size: 100% 100%;

  .register-header {
    position: absolute;
    top: 0;
    display: flex;
    justify-content: right;
    width: 100%;
    padding: 15px;
  }

  .register-form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 460px;
    padding: 40px;
    overflow: hidden;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: var(--el-box-shadow-light);

    @media (width <= 460px) {
      width: 100%;
      padding: 20px;
    }

    .form-title {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 0 20px;
      text-align: center;
    }

    .input-wrapper {
      display: flex;
      align-items: center;
      width: 100%;
    }

    .avatar-uploader {
      width: 100%;
      :deep(.el-upload) {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);

        &:hover {
          border-color: var(--el-color-primary);
        }
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 120px;
        height: 120px;
        text-align: center;
      }
      .avatar {
        width: 120px;
        height: 120px;
        display: block;
      }
    }
  }
}

:deep(.el-form-item) {
  background: var(--el-input-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      transition: background-color 1000s ease-in-out 0s;
    }
  }
}

html.dark {
  .register {
    background: url("@/assets/images/login-bg-dark.jpg") no-repeat center right;

    .register-form {
      background: transparent;
      box-shadow: var(--el-box-shadow);
    }
  }
}
</style>
